const { ethers } = require('ethers');

// 配置
const RPC_URL = 'https://data-seed-prebsc-1-s1.binance.org:8545/';
const CONTRACT_ADDRESS = '0x031b8B821B0F1A87D1a1451479d29660Bc68d2C8';

// 合约ABI（只需要我们要用的方法）
const CONTRACT_ABI = [
  "function tokenLaunches(uint256) view returns (address tokenAddress, address creator, string name, string symbol, string description, string website, string telegram, string twitter, uint256 targetAmount, uint256 raisedAmount, uint256 tokensSold, uint256 createdAt, uint256 deadline, bool launched, bool cancelled, uint256 bondingCurveK, uint256 totalSupplyForSale)",
  "function getCurrentTokenPrice(uint256 _launchId) view returns (uint256)",
  "function calculateTokensForBNB(uint256 _launchId, uint256 _bnbAmount) view returns (uint256)",
  "function calculateBNBForTokens(uint256 _launchId, uint256 _tokenAmount) view returns (uint256)"
];

async function checkContractStatus() {
  try {
    // 连接到BSC测试网
    const provider = new ethers.JsonRpcProvider(RPC_URL);
    const contract = new ethers.Contract(CONTRACT_ADDRESS, CONTRACT_ABI, provider);

    console.log('=== 合约状态检查 ===');
    
    // 检查合约BNB余额
    const contractBalance = await provider.getBalance(CONTRACT_ADDRESS);
    console.log(`合约BNB余额: ${ethers.formatEther(contractBalance)} BNB`);
    
    // 检查Launch ID 2的详细信息
    const launchId = 2;
    try {
      const launch = await contract.tokenLaunches(launchId);
      console.log(`\n=== Launch ID ${launchId} 信息 ===`);
      console.log(`代币地址: ${launch.tokenAddress}`);
      console.log(`创建者: ${launch.creator}`);
      console.log(`名称: ${launch.name}`);
      console.log(`目标金额: ${ethers.formatEther(launch.targetAmount)} BNB`);
      console.log(`已筹集: ${ethers.formatEther(launch.raisedAmount)} BNB`);
      console.log(`已出售代币: ${ethers.formatUnits(launch.tokensSold, 18)} tokens`);
      console.log(`是否已启动: ${launch.launched}`);
      console.log(`是否已取消: ${launch.cancelled}`);
      
      // 获取当前价格
      const currentPrice = await contract.getCurrentTokenPrice(launchId);
      console.log(`当前代币价格: ${ethers.formatEther(currentPrice)} BNB/token`);
      
      // 计算100个代币能卖多少BNB
      const tokenAmount = ethers.parseUnits('100', 18);
      const bnbForTokens = await contract.calculateBNBForTokens(launchId, tokenAmount);
      console.log(`100个代币可卖出: ${ethers.formatEther(bnbForTokens)} BNB`);
      
      // 检查合约是否有足够余额
      if (contractBalance >= bnbForTokens) {
        console.log('✅ 合约有足够BNB余额进行卖出');
      } else {
        console.log('❌ 合约BNB余额不足，需要更多购买操作');
        console.log(`缺少: ${ethers.formatEther(bnbForTokens - contractBalance)} BNB`);
      }
      
    } catch (error) {
      console.log(`Launch ID ${launchId} 不存在或出错:`, error.message);
    }
    
  } catch (error) {
    console.error('检查失败:', error);
  }
}

checkContractStatus();
